import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;

import com.java4less.rchart.Chart;
import com.java4less.rchart.ChartAdapter;
import com.java4less.rchart.ChartListener;
import com.java4less.rchart.ChartLoader;
import com.java4less.rchart.gc.awt.ChartAwt1Image;
import com.java4less.rchart.swing.JChartViewer;


/**
 * Sample application for displaying charts in Swing
 */
public class JExamples extends JFrame implements ActionListener {
	
	JChartViewer chartViewer= new JChartViewer();
	
	JMenuBar menuBar = new JMenuBar();
	JMenu menuFile = new JMenu();
	JMenu menuExamplesAPI = new JMenu();
	JMenu menuExamplesLoader = new JMenu();
	JMenuItem itemLoad = new JMenuItem();
	JMenuItem itemSave = new JMenuItem();
	JMenuItem itemExit = new JMenuItem();	
	
	JMenuItem itemExample0= new JMenuItem();
	JMenuItem itemExample1= new JMenuItem();
	JMenuItem itemExample2= new JMenuItem();
	JMenuItem itemExample3= new JMenuItem();
	JMenuItem itemExample4= new JMenuItem();
	JMenuItem itemExample5= new JMenuItem();
	JMenuItem itemExample6= new JMenuItem();
	JMenuItem itemExample7= new JMenuItem();
	JMenuItem itemExample8= new JMenuItem();
	JMenuItem itemExample9= new JMenuItem();
	JMenuItem itemExample10= new JMenuItem();
	JMenuItem itemExample11= new JMenuItem();
	JMenuItem itemExample12= new JMenuItem();
	JMenuItem itemExample13= new JMenuItem();
	JMenuItem itemExample14= new JMenuItem();
	JMenuItem itemExample15= new JMenuItem();
	
	JMenuItem itemLoader0= new JMenuItem();
	JMenuItem itemLoader1= new JMenuItem();
	JMenuItem itemLoader2= new JMenuItem();
	JMenuItem itemLoader3= new JMenuItem();
	JMenuItem itemLoader4= new JMenuItem();
	JMenuItem itemLoader5= new JMenuItem();
	JMenuItem itemLoader6= new JMenuItem();
	JMenuItem itemLoader7= new JMenuItem();
	JMenuItem itemLoader8= new JMenuItem();
	JMenuItem itemLoader9= new JMenuItem();
	JMenuItem itemLoader10= new JMenuItem();
	JMenuItem itemLoader11= new JMenuItem();
	JMenuItem itemLoader12= new JMenuItem();
	JMenuItem itemLoader13= new JMenuItem();
	JMenuItem itemLoader14= new JMenuItem();
	JMenuItem itemLoader15= new JMenuItem();
	JMenuItem itemLoader16= new JMenuItem();
	JMenuItem itemLoader17= new JMenuItem();
	JMenuItem itemLoader18= new JMenuItem();
	JMenuItem itemLoader19= new JMenuItem();
	JMenuItem itemLoader20= new JMenuItem();
	JMenuItem itemLoader21= new JMenuItem();
	JMenuItem itemLoader22= new JMenuItem();
	JMenuItem itemLoader23= new JMenuItem();
	JMenuItem itemLoader24= new JMenuItem();
	JMenuItem itemLoader25= new JMenuItem();
	JMenuItem itemLoader26= new JMenuItem();
	
	// create chart listener 
	ChartAdapter chartAdapter=new ChartAdapter() {
					public void chartEvent(Chart c,int type) {
						if (type==ChartListener.EVENT_POINT_CLICKED) {
							JOptionPane.showMessageDialog(JExamples.this,"You just clicked on series "+ c.selectedSerie.name.toUpperCase() + " point "+ (c.selectedSeriePoint+1),"Point clicked",JOptionPane.INFORMATION_MESSAGE);
						}
						
						// rebuild chart with new data
						if (type==ChartListener.EVENT_BEFORE_UPDATE) {
							// // get a new random value between 0 and 40 and update 3 of the values in the serie
							int newValue=(int) (System.currentTimeMillis() % 40); 
							c.plotters[0].getSerie(0).replaceYValueAt(1,newValue);
							c.plotters[0].getSerie(0).replaceYValueAt(2,newValue+10);
							c.plotters[0].getSerie(0).replaceYValueAt(3,newValue-10);							

							// do not allow the chart to be rebuilt from the original parameters
							c.autoRebuild=false;
							
							// an alternative would be:
							// set new parameter
							//c.loader.setParameter("SERIE_DATA_1","10|20|30 ....");
							// rebuild chart from parameters
							// c.autoRebuild=true;
												
						}						
						
					}
				};	
				
	// create chart listener for the drill down chart
	ChartAdapter chartAdapterDrillDown=new ChartAdapter() {
						public void chartEvent(Chart c,int type) {
							// load subchart
							if (type==ChartListener.EVENT_POINT_CLICKED) {		
								if (c.selectedSeriePoint==0) loadNewChart(null,"examples/subpie1.txt");
								else if (c.selectedSeriePoint==1) loadNewChart(null,"examples/subpie2.txt");
								else if (c.selectedSeriePoint==2) loadNewChart(null,"examples/subpie3.txt");		
							}						
						}
					};	
	
	// create chart listener for the drill down chart
	ChartAdapter chartAdapterRealtime=new ChartAdapter() {
						public void chartEvent(Chart c,int type) {
							// load subchart
							if (type==ChartListener.EVENT_BEFORE_UPDATE) createRealtimedata(chartViewer.getChart().loader);
						}
					};		
	
	
	public static void main(String[] args) {
		JExamples demo=new JExamples();
		demo.show();
	}		
	
	public JExamples() {
		this.setTitle("RChart for Swing example");
		this.setResizable(false);
		this.setJMenuBar(menuBar);
		this.getContentPane().setLayout(new java.awt.BorderLayout());
		this.setSize(new Dimension(500,500));			
		this.getContentPane().add("Center", chartViewer);
		
		
		menuBar.add(menuFile);
		menuBar.add(menuExamplesAPI);
		menuBar.add(menuExamplesLoader);
		
		menuFile.setText("File");
		menuExamplesAPI.setText("Examples Java API");
		menuExamplesLoader.setText("Examples Loader");
		
		menuFile.add(itemLoad);
		menuFile.add(itemSave);
		menuFile.add(itemExit);
		
		itemLoad.setText("Load chart");
		itemSave.setText("Save as JPG");
		itemExit.setText("Exit");
		
		menuExamplesAPI.add(itemExample0);
		menuExamplesAPI.add(itemExample1);
		menuExamplesAPI.add(itemExample2);
		menuExamplesAPI.add(itemExample3);
		menuExamplesAPI.add(itemExample4);
		menuExamplesAPI.add(itemExample5);
		menuExamplesAPI.add(itemExample6);
		menuExamplesAPI.add(itemExample7);
		menuExamplesAPI.add(itemExample8);
		menuExamplesAPI.add(itemExample9);
		menuExamplesAPI.add(itemExample10);
		menuExamplesAPI.add(itemExample11);
		menuExamplesAPI.add(itemExample12);
		menuExamplesAPI.add(itemExample13);
		menuExamplesAPI.add(itemExample14);
		menuExamplesAPI.add(itemExample15);
		
		menuExamplesLoader.add(itemLoader21);
		menuExamplesLoader.add(itemLoader22);
		menuExamplesLoader.add(itemLoader23);
		menuExamplesLoader.add(itemLoader24);
		menuExamplesLoader.add(itemLoader25);
		menuExamplesLoader.add(itemLoader26);
		menuExamplesLoader.add(itemLoader20);		
		menuExamplesLoader.add(itemLoader0);
		menuExamplesLoader.add(itemLoader1);
		menuExamplesLoader.add(itemLoader2);
		menuExamplesLoader.add(itemLoader3);
		menuExamplesLoader.add(itemLoader4);
		menuExamplesLoader.add(itemLoader5);
		menuExamplesLoader.add(itemLoader6);
		menuExamplesLoader.add(itemLoader7);
		menuExamplesLoader.add(itemLoader8);
		menuExamplesLoader.add(itemLoader9);
		menuExamplesLoader.add(itemLoader10);
		menuExamplesLoader.add(itemLoader11);
		menuExamplesLoader.add(itemLoader12);
		menuExamplesLoader.add(itemLoader13);
		menuExamplesLoader.add(itemLoader14);
		menuExamplesLoader.add(itemLoader15);
		menuExamplesLoader.add(itemLoader16);
		menuExamplesLoader.add(itemLoader17);
		menuExamplesLoader.add(itemLoader18);
		menuExamplesLoader.add(itemLoader19);
		

		itemExample0.setText("Columns with Tips (zoom and scroll)");	
		itemExample1.setText("Linechart (clipped and transparent)");			
		itemExample2.setText("Horiz. Bars");			
		itemExample3.setText("Pie chart");			
		itemExample4.setText("Pie chart 3D");			
		itemExample5.setText("Area chart");			
		itemExample6.setText("Bar chart");			
		itemExample7.setText("Stacked bars");			
		itemExample8.setText("Bar chart 3D (with negative bar)");			
		itemExample9.setText("Line chart 3D (gradient background)");			
		itemExample10.setText("Combined");			
		itemExample11.setText("OCHL");			
		itemExample12.setText("Radar chart (transparent filling)");			
		itemExample13.setText("Bubble chart");			
		itemExample14.setText("Max./Min.");			
		itemExample15.setText("Curves and least square");	

		itemLoader0.setText("Combined chart, two Y axis, vertical labels");	
		itemLoader1.setText("Gauge");	
		itemLoader2.setText("Events (dates on axis)");					
		itemLoader3.setText("Radar chart");	
		itemLoader4.setText("Area chart (multiline axis labels)");			
		itemLoader5.setText("Line chart (clickable points and line styles)");			
		itemLoader6.setText("Line chart 3D (with rotated axis labels)");			
		itemLoader7.setText("Pie chart 3D");	
		itemLoader8.setText("Bar chart 3D (with realtime update)");	
		itemLoader9.setText("Bar chart (different colors)");	
		itemLoader10.setText("Scatter chart (with frame axis)");	
		itemLoader11.setText("Bubble chart");			
		itemLoader12.setText("Area Chart (log scale)");	
		itemLoader13.setText("Curves (B-SP Lines) with filling");	
		itemLoader14.setText("Candlestick");	
		itemLoader15.setText("Combined chart (show position as tip)");	
		itemLoader16.setText("Stacked bar chart (suppress labels)");	
		itemLoader17.setText("X Axis on top (and multiline Tips)");	
		itemLoader18.setText("Line chart with NULL values");			
		itemLoader19.setText("Drill down Chart");
		itemLoader20.setText("Realtime Chart with time axis");		
		itemLoader21.setText("Several Y Axis and target zone");
		itemLoader22.setText("Plotter Target zones");
		itemLoader23.setText("Images , notes and gradients");
		itemLoader24.setText("Pattern filling and note");
		itemLoader25.setText("4 subcharts");
		itemLoader26.setText("Stacked axis");
		
		itemExample0.addActionListener(this);
		itemExample1.addActionListener(this);
		itemExample2.addActionListener(this);
		itemExample3.addActionListener(this);
		itemExample4.addActionListener(this);
		itemExample5.addActionListener(this);
		itemExample6.addActionListener(this);
		itemExample7.addActionListener(this);
		itemExample8.addActionListener(this);
		itemExample9.addActionListener(this);
		itemExample10.addActionListener(this);
		itemExample11.addActionListener(this);
		itemExample12.addActionListener(this);
		itemExample13.addActionListener(this);
		itemExample14.addActionListener(this);
		itemExample15.addActionListener(this);
	
		itemLoader0.addActionListener(this);
		itemLoader1.addActionListener(this);
		itemLoader2.addActionListener(this);
		itemLoader3.addActionListener(this);
		itemLoader4.addActionListener(this);
		itemLoader5.addActionListener(this);
		itemLoader6.addActionListener(this);
		itemLoader7.addActionListener(this);
		itemLoader8.addActionListener(this);
		itemLoader9.addActionListener(this);
		itemLoader10.addActionListener(this);
		itemLoader11.addActionListener(this);
		itemLoader12.addActionListener(this);
		itemLoader13.addActionListener(this);
		itemLoader14.addActionListener(this);
		itemLoader15.addActionListener(this);
		itemLoader16.addActionListener(this);
		itemLoader17.addActionListener(this);
		itemLoader18.addActionListener(this);
		itemLoader19.addActionListener(this);
		itemLoader20.addActionListener(this);
		itemLoader21.addActionListener(this);	
		itemLoader22.addActionListener(this);	
		itemLoader23.addActionListener(this);	
		itemLoader24.addActionListener(this);	
		itemLoader25.addActionListener(this);	
		itemLoader26.addActionListener(this);			
		
		itemLoad.addActionListener(this);	
		itemSave.addActionListener(this);	
		itemExit.addActionListener(this);				
		
		
		this.doLayout();
		
		// create default chart
		chartViewer.setChart(ChartExamples.getDefaultChart());
		
		// in case we use JDK 1.1
		ChartAwt1Image.visibleComponent=this;		
	}
	
	public void actionPerformed(ActionEvent e) {
		if (e.getSource()== itemExit) {
				// finish program
				chartViewer.getChart().stopUpdater();
				this.hide();
				System.exit(0);
		}
		else if (e.getSource()== itemSave) {
			
			// save file to bmp
				try {
				chartViewer.getChart().saveToFile("chart.jpg","JPG");
				//chartViewer.getChart().saveToFile("chart.gif","GIF");
	
				JOptionPane.showMessageDialog(this,"Chart has been save to chart.jpg. We recommend however the GIF or PNG formats","Export to image",JOptionPane.INFORMATION_MESSAGE);	

			
				} catch (Exception err) {
					err.printStackTrace();				
					JOptionPane.showMessageDialog(this,"Could not export chart: "+ err.getMessage(),"Export to image",JOptionPane.INFORMATION_MESSAGE);
				}			
			
		}
		else loadNewChart(e.getSource(),null);
	}
	
	
	/**
	 * a new menu item has been selected, load new chart
	 * @param menuItem
	 * @param dataFile chartfile to load
	 */
	private void loadNewChart(Object menuItem,String dataFile) {
		
		Chart c=null;
		String fileToLoad=dataFile;
		
		if (menuItem==this.itemExample0) c=ChartExamples.getDefaultChart();
		if (menuItem==this.itemExample1) c=ChartExamples.Example1();
		if (menuItem==this.itemExample2) c=ChartExamples.Example2();
		if (menuItem==this.itemExample3) c=ChartExamples.Example3();
		if (menuItem==this.itemExample4) c=ChartExamples.Example4();
		if (menuItem==this.itemExample5) c=ChartExamples.Example5();
		if (menuItem==this.itemExample6) c=ChartExamples.Example6();
		if (menuItem==this.itemExample7) c=ChartExamples.Example7();
		if (menuItem==this.itemExample8) c=ChartExamples.Example8();
		if (menuItem==this.itemExample9) c=ChartExamples.Example9();
		if (menuItem==this.itemExample10) c=ChartExamples.Example10();
		if (menuItem==this.itemExample11) c=ChartExamples.Example11();
		if (menuItem==this.itemExample12) c=ChartExamples.Example12();
		if (menuItem==this.itemExample13) c=ChartExamples.Example13();
		if (menuItem==this.itemExample14) c=ChartExamples.Example14();
		if (menuItem==this.itemExample15) c=ChartExamples.Example15();
		if (menuItem==this.itemLoader0) fileToLoad="examples/combinedChart.txt";
		if (menuItem==this.itemLoader1) fileToLoad="examples/gauge.txt";
		if (menuItem==this.itemLoader2) fileToLoad="examples/event.txt";
		if (menuItem==this.itemLoader3) fileToLoad="examples/radarChart.txt";
		if (menuItem==this.itemLoader4) fileToLoad="examples/areaChart.txt";
		if (menuItem==this.itemLoader5) fileToLoad="examples/lineChart.txt";
		if (menuItem==this.itemLoader6) fileToLoad="examples/lineChart3D.txt";
		if (menuItem==this.itemLoader7) fileToLoad="examples/pieChart3D.txt";
		if (menuItem==this.itemLoader8) fileToLoad="examples/barChart3D.txt";
		if (menuItem==this.itemLoader9) fileToLoad="examples/barChart.txt";
		if (menuItem==this.itemLoader10) fileToLoad="examples/scatterChart.txt";
		if (menuItem==this.itemLoader11) fileToLoad="examples/bubbleChart.txt";
		if (menuItem==this.itemLoader12) fileToLoad="examples/areaChartLog.txt";
		if (menuItem==this.itemLoader13) fileToLoad="examples/areaCurves.txt";
		if (menuItem==this.itemLoader14) fileToLoad="examples/candleStick.txt";
		if (menuItem==this.itemLoader15) fileToLoad="examples/combined2Positions.txt";
		if (menuItem==this.itemLoader16) fileToLoad="examples/stackedBar.txt";
		if (menuItem==this.itemLoader17) fileToLoad="examples/axisOnTop.txt";
		if (menuItem==this.itemLoader18) fileToLoad="examples/linechartNULLS.txt";
		if (menuItem==this.itemLoader19) fileToLoad="examples/PieDrillDown.txt";
		if (menuItem==this.itemLoader20) fileToLoad="examples/realtime.txt";
		if (menuItem==this.itemLoader21) fileToLoad="examples/MultiAxis.txt";
		if (menuItem==this.itemLoader22) fileToLoad="examples/targetZones.txt";
		if (menuItem==this.itemLoader23) fileToLoad="examples/barImages.txt";
		if (menuItem==this.itemLoader24) fileToLoad="examples/patternFilling.txt";
		if (menuItem==this.itemLoader25) fileToLoad="examples/MultiCharts.txt";
		if (menuItem==this.itemLoader26) fileToLoad="examples/StackedMultiAxis.txt";
		
				
		// allow user selection of file
		if (menuItem==this.itemLoad) {
			String[] f=getFileName("Select File to be loaded",".","",false);
			if (f!=null)
			if (new File(f[1]+f[0]).exists()) fileToLoad="file:///"+f[1]+f[0];
		}
		
	//		load new chart from file
		if (fileToLoad!=null) {
				ChartLoader loader=new ChartLoader();
				loader.loadFromFile(fileToLoad,true);
				if (menuItem==this.itemLoader20) this.createRealtimedata(loader);
				c=loader.build(false,false);		
		}
		

					

		
		// set new chart, enable zoom for certain examples
		chartViewer.changePointer=false;
		chartViewer.allowZoom=false;
		if (c!=null) {
			
			if (menuItem==this.itemExample0) 
				chartViewer.allowZoom=true;
			
			// set clicked point listener
			if (menuItem==this.itemLoader5) {
				c.addChartListener(chartAdapter);
				c.activateSelection=true;
				chartViewer.changePointer=true;
			}
			
			// set listener for drill down example
			if (menuItem==this.itemLoader19) {
				c.addChartListener(chartAdapterDrillDown);
				c.activateSelection=true;
				chartViewer.changePointer=true;				
			}
			
			// set listener for realtime update example
			if (menuItem==this.itemLoader8) c.addChartListener(chartAdapter);				
			if (menuItem==this.itemLoader20) c.addChartListener(chartAdapterRealtime);
						
			// enable zoom
			if (menuItem==this.itemLoader6) chartViewer.allowZoom=true; 
			
			chartViewer.getChart().stopUpdater();
			// stop update thread of previous chart			
			chartViewer.setChart(c);
			
			chartViewer.redrawChart();
			
			// real time update example, start update thread
			if ((menuItem==this.itemLoader8) || (menuItem==this.itemLoader20))  c.startUpdater();			
			
		} 
		
	
	}
	
	/**
	 * displays file dialog
	 * @param t text
	 * @param initDir intial directory
	 * @param initFile initial file
	 * @param save save mode?
	 * @return selected file
	 */
	private String[] getFileName(String t,String initDir, String initFile,boolean save) {
		
		FileDialog fd=new FileDialog(this,t);
		String[] result= new String[2];
		
		if (initDir.length()>0) fd.setDirectory(initDir);
		if (initFile.length()>0) fd.setFile(initFile);
		
		if (save) fd.setMode(FileDialog.SAVE);
		else fd.setMode(FileDialog.LOAD);
		
		try {
			
			fd.show();
			
			} catch (Exception e) {
		}
		
		// user cancelled?
		if (fd.getFile()==null) return null;
		if (fd.getFile().length()==0) return null;
		
		result[0]=fd.getFile();
		result[1]=fd.getDirectory();
		
		return result;
		
		
	}
	
	/**
	 * this method creates realtime data for the realtime example every 2 seconds
	 *
	 */
   private void createRealtimedata(ChartLoader loader) {
		//	create chart

		//	set initial valu of the X Axis based on the time
		java.util.Date now=java.util.Calendar.getInstance().getTime();
		java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("dd/MM/yy hh:mm:ss");

		loader.setParameter("XAXIS_INITIAL_DATE",formatter.format(now));


		//	create random data based on the time
		java.util.Calendar cal=java.util.Calendar.getInstance();
		String data1="";
		String data2="";
		for (int i=0;i<9;i++) {		
			cal.add(java.util.Calendar.SECOND,-2);
			if (data1.length()>0) data1="|" + data1;
			data1=""+cal.get(java.util.Calendar.SECOND)+ data1;
			if (data2.length()>0) data2="|" + data2;
			data2=""+(cal.get(java.util.Calendar.SECOND)/6)+ data2;		
		}

		loader.setParameter("SERIE_DATA_1",data1);
		loader.setParameter("SERIE_DATA_2",data2);
		

   }
}
